/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package jard.webshop.nbp;

import jard.webshop.util.Constants;
import java.io.Serializable;
import java.util.LinkedList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;

/**
 *
 * @author CJP
 */
@Entity
@NamedQueries({
        @NamedQuery(name=Constants.GET_ALL_CATS,query="SELECT c FROM Category c"),
        @NamedQuery(name=Constants.GET_ROOT_CATS,query="SELECT c FROM Category c WHERE c.parent IS NULL")
})
public class Category implements Serializable {
    
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    
    private String name = "Default category";
    
    @ManyToOne
    private Category parent;
    
    @OneToMany(cascade=CascadeType.ALL,mappedBy = "parent")
    private List<Category> subcategories = new LinkedList<Category>();
    
    public Category() {
    }

    public Category(String name) {
        this.name = name;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Category)) {
            return false;
        }
        Category other = (Category) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return name;//jard.webshop.nbp.Category[ id=" + id + " ]";
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Category getParent() {
        return parent;
    }

    public void setParent(Category parent) {
        this.parent = parent;
    }

    public List<Category> getSubcategories() {
        return subcategories;
    }

    public void setSubcategories(List<Category> subcategories) {
        this.subcategories = subcategories;
    }
    
    public void addSubcategory(Category subcategory) {
        subcategories.add(subcategory);
        subcategory.setParent(this);
    }
    
    public void removeSubcategory(Category subcategory) {
        subcategories.remove(subcategory);
    }
}
